//
//  AddTallyViewController.m
//  Exam13-2b
//
//  Created by 孙晓晔 on 2017/4/29.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "AddTallyViewController.h"
#import "TallyListView.h"
#import "CalculatorView.h"

@interface AddTallyViewController ()<TallyListViewDelegate,CalculatorViewDelegate>
@property(nonatomic,strong) TallyListView *listView;
@property(nonatomic,strong) CalculatorView *calView;

@property(nonatomic,strong) Tally *currentTally;

@property(nonatomic,assign) CGSize itemSize;

@end

#define aRowCellCount 4

@implementation AddTallyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    [self.view addSubview:self.listView];
    [self.view addSubview:self.calView];
    
    self.title = @"新增";
    
    if (self.currentTally) {
        [self.calView modifyTally:self.currentTally];
        self.title = @"修改";
    }
    
    self.automaticallyAdjustsScrollViewInsets = NO;
}

// 懒加载
-(TallyListView *)listView {
    
    if (_listView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        
        layout.minimumLineSpacing = 5; // 垂直方向的间距
        layout.minimumInteritemSpacing = 10; // 水平方向的间距
        
        layout.sectionInset = UIEdgeInsetsMake(0, 15, 0, 15);
        
        CGFloat width = (self.view.frame.size.width - (aRowCellCount - 1) *layout.minimumInteritemSpacing - layout.sectionInset.left - layout.sectionInset.right) / aRowCellCount;
        CGFloat height = width * 1.2;
        
        layout.footerReferenceSize = CGSizeZero;
        layout.headerReferenceSize = CGSizeZero;
        
        layout.itemSize = CGSizeMake(width,height);
        
        self.itemSize = CGSizeMake(width-20,width-20);
        
        _listView = [[TallyListView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64 - self.view.frame.size.height*0.4/5) collectionViewLayout:layout];
        
        _listView.tallyDelegate = self;
        
    }
    
    return _listView;
}

// 懒加载
-(CalculatorView *)calView {
    if (_calView == nil) {
        _calView = [[CalculatorView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height*0.6, self.view.frame.size.width, self.view.frame.size.height*0.4)];
        
        _calView.delegate = self;
        _calView.imageViewSize = self.itemSize;
    }
    
    return _calView;
}

#pragma mark - TallyListViewDelegate

- (void)didSelectItem:(TallyViewCell*)cell index:(NSInteger)index withRectInCollection:(CGRect)itemRect {
    
    UIImageView *animateImage = [[UIImageView alloc] initWithFrame:itemRect];
    animateImage.image = cell.imageView.image;
    
    [self.view addSubview:animateImage];
    
    __block CGPoint imgPoint;
    self.calView.positionInViewBlock = ^(CGPoint point){
        imgPoint = point;
    };
    
    //给计算器界面传值
    self.calView.imageViewSize = itemRect.size;
    
    self.calView.image = cell.imageView.image;
    self.calView.typeName = cell.imageLabel.text;
    self.calView.index = index;
    
    //设置贝塞尔曲线路径动画
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:animateImage.center];
    [path addCurveToPoint:imgPoint controlPoint1:CGPointMake(animateImage.frame.origin.x, animateImage.frame.origin.y-100 ) controlPoint2:CGPointMake(animateImage.frame.origin.x, animateImage.frame.origin.y-100 )];
    
    CAKeyframeAnimation *anmiation0 = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    anmiation0.path = path.CGPath;
    anmiation0.duration = 1;
    anmiation0.removedOnCompletion = NO;
    anmiation0.fillMode = kCAFillModeForwards;
    [animateImage.layer addAnimation:anmiation0 forKey:nil];
    
    [NSTimer scheduledTimerWithTimeInterval:1 repeats:NO block:^(NSTimer * _Nonnull timer) {
        [animateImage removeFromSuperview];
    }];
}

//计算界面下降
- (void)listScrollToBottom {
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.calView.frame = CGRectMake(0, CGRectGetHeight(self.view.frame)-CGRectGetHeight(self.calView.frame)/5, self.calView.frame.size.width, self.calView.frame.size.height);
    } completion:nil];
}

//随机转场动画
- (void)showAnimation {
    
    NSArray *tanArray = @[@"pageCurl",@"pageUnCurl",@"rippleEffect",@"suckEffect",@"cube",@"oglFlip"];
    NSString *anStr = tanArray[arc4random()%tanArray.count];
    self.navigationController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    
    CATransition *tran = [CATransition animation];
    tran.duration = 0.5;
    tran.type = anStr;
    tran.subtype = kCATransitionFromLeft;
    [self.navigationController.view.layer addAnimation:tran forKey:nil];
}

#pragma mark - CalculatorViewDelegate
//保存成功
- (void)tallySaveCompleted:(Tally*)tally {
    
    if ([self.tallyDelegate respondsToSelector:@selector(addTally:)]) {
        [self.tallyDelegate addTally:tally];
    }
    
    [self showAnimation];
    
    [self.navigationController popViewControllerAnimated:NO];
}

// 更新信息
- (void)tallyUpdateCompleted:(Tally*)tally {
    
    if ([self.tallyDelegate respondsToSelector:@selector(updateTally:)]) {
        [self.tallyDelegate updateTally:tally];
    }
    
    [self showAnimation];
    
    [self.navigationController popViewControllerAnimated:NO];
}

//保存失败
- (void)tallySaveFailed {
    UIAlertController *alertVC =[UIAlertController alertControllerWithTitle:@"提示" message:@"请选择类别并输入金额" preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

//返回位置
- (void)backPositionWithAnimation {
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.calView.frame = CGRectMake(0, self.view.frame.size.height * 0.6, self.view.frame.size.width, self.view.frame.size.height * 0.4);
    } completion:nil];
}

-(void)selectTally:(Tally*)tally {
    self.currentTally = tally;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
